package com.media.appmedia.activity;

import java.lang.reflect.Type;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.media.appmedia.R;
import com.media.appmedia.base.BaseApplication;
import com.media.appmedia.entity.BaseEntity;
import com.media.appmedia.entity.Registerben;
import com.media.appmedia.network.AbsHttpResponseHandler;
import com.media.appmedia.network.ProtocolService;
import com.media.appmedia.util.Const;
import com.media.appmedia.util.MLog;
import com.media.appmedia.util.MethodUtils;
import com.media.appmedia.util.PhoneInfoUtils;
import com.media.appmedia.util.StringUtils;
import com.media.appmedia.util.TimerDown;
import com.media.appmedia.util.ToastUtils;
import com.media.appmedia.util.UserMgr;

/**
 * 
 * <pre>
 * 业务名:
 * 功能说明: 实现注册
 * 编写日期:	2014-11-26
 * 作者:	 Rose
 * 
 * 历史记录
 * 1、修改日期：
 *    修改人：Rose
 *    修改内容：实现跳转之后结束自身
 * </pre>
 */
public class RegisterActivity extends Activity implements OnClickListener {

	public Handler handler;
	private EditText mEditTextphone, mEditTextpass, mEditTextpaoqing,
			mEditTextname;
	private Button phoneBtn, identifyBtn;
	private TimerDown timer;
	private String phone;
	private String mobId;
	private CheckBox box;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		setContentView(R.layout.register_layout);
		initView();
	}

	public void initView() {
		// 手机号输入框
		mEditTextphone = (EditText) findViewById(R.id.reg_id_edit);
		// 验证码输入框
		mEditTextpass = (EditText) findViewById(R.id.reg_pass_edit);
		// 用户名
		mEditTextname = (EditText) findViewById(R.id.yonghuming);
		
		box = (CheckBox) findViewById(R.id.check_btn);
		// //邀请码
		// mEditTextpaoqing = (EditText) findViewById(R.id.yaoqingma);
		// 验证码的获取，提交按钮
		phoneBtn = (Button) findViewById(R.id.btnPhone);
		identifyBtn = (Button) findViewById(R.id.register_btn);
		phoneBtn.setOnClickListener(this);
		identifyBtn.setOnClickListener(this);
		mEditTextphone.setInputType(EditorInfo.TYPE_CLASS_PHONE);
		mEditTextpass.setInputType(EditorInfo.TYPE_CLASS_PHONE);

	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.btnPhone:
			boolean isCanNetWork = PhoneInfoUtils.isNetworkOpen(this);
			if (!isCanNetWork) {
				ToastUtils.show(this, R.string.none_network_info);
				return;
			}
			String phoneNum = mEditTextphone.getText().toString().trim();
			if (StringUtils.isEmpty(phoneNum)) {
				ToastUtils.show(getApplicationContext(),
						R.string.phone_num_null);
				return;
			}
			if (!MethodUtils.isMobile(phoneNum)) {
				ToastUtils.show(getApplicationContext(),
						R.string.phone_num_format_error);
				return;
			}
			startTimerDown();
			// 获取验证码
			String phoneId1 = PhoneInfoUtils.getIMEI(getApplicationContext());
			getVerifyPhoneCodeData(phoneNum, phoneId1, timer);
			break;
		case R.id.register_btn:
			phone = mEditTextphone.getText().toString();
			if (StringUtils.isEmpty(phone)) {
				ToastUtils.show(getApplicationContext(),
						R.string.phone_num_null);
				return;
			}
			if (!MethodUtils.isMobile(phone)) {
				ToastUtils.show(getApplicationContext(),
						R.string.phone_num_format_error);
				return;
			}
			if(!box.isChecked()){
				ToastUtils.show(getApplicationContext(),
						"请阅读并勾选用户协议！");
				return;
				
			}
			String phoneId = mEditTextpass.getText().toString().trim();
			if (MethodUtils.isEmpty(phoneId)) {
				ToastUtils.show(getApplicationContext(),
						R.string.verify_code_null);
//				if(timer!=null){
//					timer.overTime();
//					phoneBtn.setText("今日已达上限");
//					phoneBtn.setClickable(false);
//				}
				return;
			}
			String userName = mEditTextname.getText().toString().trim();
			if (MethodUtils.isEmpty(userName)) {
				ToastUtils.show(getApplicationContext(), R.string.user_is_enty);
				return;
			}
			// 获取手机唯一标识
			mobId = PhoneInfoUtils.getIMEI(getApplicationContext());
			getVerifyPhoneCode2(phone, phoneId, userName, mobId, "5",
					 null);
			break;
		}
	}

	/**
	 * 获取验证码
	 * 
	 * @param phoneNumber
	 *            手机号
	 */
	protected void getVerifyPhoneCodeData(String phoneNumber, String type,
			final TimerDown timer) {
		ProtocolService.getVerifyPhoneCode(phoneNumber, type,
				new RequestCallBack<String>() {
					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						System.out.println("服务器数据：" + arg0.result);
						Gson gson = new Gson();
						Type type = new TypeToken<BaseEntity>() {
						}.getType();
						BaseEntity baseEntity = gson
								.fromJson(arg0.result, type);
						if (baseEntity != null) {
							if (baseEntity.isSuccess()) {
								ToastUtils.show(getApplicationContext(),
										R.string.phone_verify_send_success);
							} else if (baseEntity.getError() == 3) {
								ToastUtils.show(getApplicationContext(),
										R.string.user_not_exist);
								timer.cancel();
							} else if (baseEntity.getError() == 4) {
								ToastUtils.show(getApplicationContext(),
										R.string.user_already_register);
								timer.cancel();
							} else if (baseEntity.getError() == 6) {
								ToastUtils.show(getApplicationContext(),
										R.string.orrer_register);
								timer.cancel();
							} else if (baseEntity.getError() == Const.OFF_USER_ERROR_NUM) {
								timer.cancel();
								if (baseEntity.getError() != 2)
									ToastUtils.show(getApplicationContext(),
											baseEntity.getMessage());
							} else {
								timer.cancel();
								if (baseEntity.getError() == 1)
									ToastUtils.show(getApplicationContext(),
											R.string.user_already_register);
							}
						} else {
							ToastUtils.show(getApplicationContext(),
									R.string.phone_verify_send_fail);
						}
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						ToastUtils.show(getApplicationContext(),
								R.string.phone_verify_send_fail);
						timer.cancel();
					}
				});
	}

	/**
	 * 
	 * 方法说明：
	 * 
	 * @param cellphone
	 *            手机号码
	 * @param verfiycode
	 *            验证码
	 * @param userMac
	 *            用户名
	 * @param shId
	 *            手机标示符
	 * @param source
	 *            来源途径
	 * @param deviceType
	 * @param one_shang
	 *            邀请码
	 * @param handler
	 */
	protected void getVerifyPhoneCode2(String cellphone, String verfiycode,
			String userMac, String shId, String source,
			RequestCallBack<String> handler) {
		ProtocolService.register(cellphone, verfiycode, userMac, shId, source,
				 new AbsHttpResponseHandler(RegisterActivity.this) {
					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						MLog.d("注册" + arg0.result);
						Gson gson = new Gson();
						Type type = new TypeToken<Registerben>() {
						}.getType();
						Registerben entity = gson.fromJson(arg0.result, type);
						if (entity != null) {
							if (entity.getError() == 0) {
								ToastUtils.show(getApplicationContext(),
										R.string.register_success);
								String userID = entity.getUserCode();
								UserMgr.getInstance().setLogin(true);
								UserMgr.getInstance().setUserID(userID);
								MethodUtils.saveAutoLoginConfig(
										getApplicationContext(), true);
								setResult(Activity.RESULT_OK);
								Intent i = new Intent(RegisterActivity.this,
										MainActivity.class);
								startActivity(i);
								MethodUtils.setUserInfo(
										getApplicationContext(), phone);
								BaseApplication.getApplication().setUserPhone(
										phone);
								BaseApplication.getApplication()
										.setMobId(mobId);
								RegisterActivity.this.finish();
							} else {
								if (entity.getError() == 5) { // 验证码失效
									ToastUtils.show(getApplicationContext(),
											R.string.register_verify_due);
								} else if (entity.getError() == 2) { // 验证码错误
									ToastUtils.show(getApplicationContext(),
											R.string.register_verify_error);
								} else if (entity.getError() == 4) { // 手机号错误
									ToastUtils.show(getApplicationContext(),
											R.string.register_phone_error);
								} else {
									ToastUtils.show(getApplicationContext(),
											R.string.register_fail);
								}
							}
						} else {
							ToastUtils.show(getApplicationContext(),
									R.string.register_fail);
						}
						super.onSuccess(arg0);
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						ToastUtils.show(getApplicationContext(),
								R.string.register_fail);
						super.onFailure(arg0, arg1);
					}
				});
	}

	/** 点击获取验证码按钮后,开启倒计时功能 */
	private void startTimerDown() {
		phoneBtn.setEnabled(false);
		timer = new TimerDown(new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case TimerDown.DOWN_PROGRESS_MSG:
					phoneBtn.setText(getString(R.string.down_timer, msg.arg1));
					break;
				case TimerDown.DOWN_OVER_MSG:
					phoneBtn.setText(getString(R.string.get_authenticode));
					phoneBtn.setEnabled(true);
					break;
				}
			}
		});
		timer.start();
	}

}
